import {Page} from '@/base/Page';
import {deleteAgent, getAgentList} from '@/base/api/AgentApi';
import {Agent} from '@/base/model/Agent';
import {isEmpty} from '@/base/util/Strings';

class Form {
  agentName = '';
  linkName = '';
  phone = '';
  createBegin = '';
  createEnd = '';
  date = [];
  roleId = '';
  companyId = [];
}

export class ListBloc {
  form = new Form();
  isShowPsdModal = false;
  agentId = 0;
  paged: Page<Agent> = new Page<Agent>([], 0, 1, 15, 0, []);
  loading = false;

  load(pageIndex: number, pageSize: number) {
    if (!isEmpty(this.form.date) && !isEmpty(String(this.form.date[0]))) {
      // @ts-ignore
      this.form.createBegin = this.form.date[0].getTime() || '';
      // @ts-ignore
      this.form.createEnd = this.form.date[1].getTime() + 24 * 60 * 60 * 1000 || '';
    } else {
      this.form.createBegin = '';
      this.form.createEnd = '';
    }
    this.loading = true;
    return getAgentList({
      pageIndex,
      pageSize,
      sortDirection: 'DESC',
      sortProperties: ['companyId', 'created'],
      agentName: this.form.agentName,
      linkName: this.form.linkName,
      phone: this.form.phone,
      createBegin: this.form.createBegin,
      createEnd: this.form.createEnd,
      companyId: this.form.companyId
    }).then((res) => {
      this.paged = res.data;
    }).finally(() => {
      this.loading = false;
    });
  }

  removeItem(dateItem: Agent) {
    this.loading = true;
    return deleteAgent(dateItem.id)
      .finally(() => {
        this.loading = false;
      });
  }

  reset() {
    this.form = new Form();
    this.paged.pageIndex = 1;
    this.paged.pageSize = 15;
    this.load(this.paged.pageIndex, this.paged.pageSize);
  }
  changePsdModal(id: number) {
    this.isShowPsdModal = true;
    this.agentId = id;
  }
  savePwdModal() {
    this.isShowPsdModal = false;
    this.load(this.paged.pageIndex, this.paged.pageSize);
  }

  getCompanyName(companyId: number) {
    const item = this.paged.extras.find(x => x.id === companyId);
    return item == null ? '' : item.name;
  }

}
